package drds.global_transaction.global_transaction_manager.api;

import drds.global_transaction.api.global_transaction_id_context.GlobalTransactionIdContexts;

public class GlobalTransactionContext
{

	private static final ThreadLocal<GlobalTransaction> globalTransactionThreadLocal = new ThreadLocal<>();

	public static void clean()
	{
		globalTransactionThreadLocal.remove();
		GlobalTransactionIdContexts.unbind();
	}

	/**
	 * need use global transaction manager to global transaction begin
	 */
	private static GlobalTransaction createNewGlobalTransaction()
	{
		GlobalTransaction globalTransaction = new GlobalTransactionImpl();
		globalTransactionThreadLocal.set(globalTransaction);
		return globalTransactionThreadLocal.get();
	}

	public static GlobalTransaction getCurrentGlobalTransaction()
	{
		// use existed
		GlobalTransaction globalTransaction = globalTransactionThreadLocal.get();
		if (globalTransaction != null)
		{
			return globalTransaction;
		}
		// globalTransactionIdWithAddressAndPort==null ?
		String globalTransactionIdWithAddressAndPort = GlobalTransactionIdContexts.getGlobalTransactionIdWithAddressAndPort();
		if (globalTransactionIdWithAddressAndPort == null)
		{
			return null;
		}
		// participant
		globalTransaction = new GlobalTransactionImpl(globalTransactionIdWithAddressAndPort);
		globalTransactionThreadLocal.set(globalTransaction);
		return globalTransactionThreadLocal.get();
	}

	public static GlobalTransaction getCurrentOrCreateGlobalTransaction()
	{
		GlobalTransaction globalTransaction = getCurrentGlobalTransaction();
		if (globalTransaction == null)
		{
			return createNewGlobalTransaction();
		}
		return globalTransaction;
	}

	private GlobalTransactionContext()
	{
	}
}
